﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using zbus; 
using GtaAPIClient.DoRZRJOrderService;
using GtaAPIClient.DoRZRJQueryService;
using GtaAPIClient.WcfRZRJBasicProviderService;

namespace GtaAPIClient
{
    class RzrjManage
    {
        WcfService wcfService = null;  
        ServiceConsole.UpdateTextDelegate delg = null;

        public RzrjManage()
        {
            wcfService = new WcfServiceImpl();
        }

        public RzrjManage(ServiceConsole.UpdateTextDelegate delg)
        {
            this.delg = delg;
            delg.BeginInvoke("RzrjManage服务初始化成功", null, null);
            wcfService = new WcfServiceImpl();
        }

        public void test()
        {
            getTradeMaxAmount("010001028412", "510300", 2.469M, 0, 14);
            //getRzrjCapital("010001028412", "2pWykA57hsE=");
            //getRzrjCreditAsset("10284", "2pWykA57hsE=");
        }

        private DoRZRJOrderService.TypesRZRJOrderEntrustType getEntrustType(int entrustType)
        {
            DoRZRJOrderService.TypesRZRJOrderEntrustType res = DoRZRJOrderService.TypesRZRJOrderEntrustType.MONEYSECURITYCancle;
            switch(entrustType)
            {
                case 10 : res = DoRZRJOrderService.TypesRZRJOrderEntrustType.BORROWMONEYTOBUY; break;
                case 11 : res = DoRZRJOrderService.TypesRZRJOrderEntrustType.BORROWSECURITYTOSELL; break;
                case 12 : res = DoRZRJOrderService.TypesRZRJOrderEntrustType.DIRECTMONEYPAIDOFF; break;
                case 13 : res = DoRZRJOrderService.TypesRZRJOrderEntrustType.SELLSECURITYFORMONEYDEBT; break;
                case 14 : res = DoRZRJOrderService.TypesRZRJOrderEntrustType.GETSECURITYFORSECURITYDEBT; break;
                case 15 : res = DoRZRJOrderService.TypesRZRJOrderEntrustType.DIRECTSECURITYPAIDOFF; break;
                case 16 : res = DoRZRJOrderService.TypesRZRJOrderEntrustType.BUYONCREDIT; break;
                case 17 : res = DoRZRJOrderService.TypesRZRJOrderEntrustType.SELLONCREDIT; break; 
                default : break;
            }
            return res;
        }
         
        [Remote("rzrjDoOrder")]
        public RZRJOrderResponse rzrjDoOrder(string capitalAccount, string stockCode, int buySell, int entrustType,
                decimal orderQuty, decimal orderPrice, int unit, int marketPrice, string PortfoliosId, string traderId, string traderPassword)
        {
            if (entrustType < 10 || entrustType > 17) 
            {
                RZRJOrderResponse res = new RZRJOrderResponse();
                res.IsSuccess = false;
                res.OrderMessage = "委托类型错误";
                return res;
            }

            try
            { 
                DoRZRJOrderService.RZRJOrderRequest orderInfo = new DoRZRJOrderService.RZRJOrderRequest();
                orderInfo.BuySell = buySell == 1 ? DoRZRJOrderService.TypesTransactionDirection.Buying : DoRZRJOrderService.TypesTransactionDirection.Selling;
                //orderInfo.ChannelID = "";
                if (!string.IsNullOrEmpty(stockCode))
                {
                    orderInfo.Code = stockCode;
                }
                orderInfo.FundAccountId = capitalAccount;
                //orderInfo.LiabilitiesNums = new string[] { };
                orderInfo.MarketPriceType = marketPrice == 1 ? DoRZRJOrderService.TypesMarketPriceType.MarketPrice : DoRZRJOrderService.TypesMarketPriceType.otherPrice;
                orderInfo.OrderEntrustType = getEntrustType(entrustType);
                if (!string.IsNullOrEmpty(stockCode) && (stockCode.StartsWith("1") || stockCode.StartsWith("5")))
                {
                    orderInfo.OrderUnitType = DoRZRJOrderService.TypesUnitType.Share;
                } 
                else 
                {
                    orderInfo.OrderUnitType = DoRZRJOrderService.TypesUnitType.Thigh;
                }
                orderInfo.OrderAmount = orderQuty;
                orderInfo.OrderPrice = orderPrice;
                orderInfo.PortfoliosId = PortfoliosId;
                orderInfo.TraderId = traderId;
                orderInfo.TraderPassword = traderPassword; 
                 
                RZRJOrderResponse res = wcfService.rzrjDoOrder(orderInfo);
                return res;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券下单失败" + ex.Message, null, null);
                throw new Exception("融资融券下单失败", ex);
            }
        }

        [Remote("rzrjCancelOrder")]
        public RzrjCancelOrderResult rzrjCancelOrder(string orderId)
        {
            try
            {
                string message = "";
                bool isSuccess = wcfService.rzrjCancelOrder(orderId, ref message);

                RzrjCancelOrderResult res = new RzrjCancelOrderResult();
                res.IsSuccess = isSuccess;
                res.Message = message;
                return res;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券撤单失败" + ex.Message, null, null);
                throw new Exception("融资融券撤单失败", ex);
            }
        }

        [Remote("rzrjGetTradeMaxAmount")]
        public TradeMaxAmountResult getTradeMaxAmount(string capitalAccount, string stockCode, decimal orderPrice, int marketPrice, int entrustType)
        {
            TradeMaxAmountResult rtn = new TradeMaxAmountResult();

            if (entrustType < 10 || entrustType > 17)
            {
                rtn.IsSuccess = false;
                rtn.ErrorMsg = "传入业务标志错误";
                return rtn;
            }

            try
            {
                RZRQComputeAmount result = new RZRQComputeAmount();
                result.CapitalAccount = capitalAccount;
                if (!string.IsNullOrEmpty(stockCode))
                {
                    result.Code = stockCode;
                }
                result.CurrencyType = DoRZRJQueryService.TypesCurrencyType.RMB;
                result.EntrustPrice = orderPrice;
                result.PriceType = marketPrice == 1 ? DoRZRJQueryService.TypesMarketPriceType.MarketPrice : DoRZRJQueryService.TypesMarketPriceType.otherPrice;
                result.OrderEntrustType = (DoRZRJQueryService.TypesRZRJOrderEntrustType)getEntrustType(entrustType);

                //result.OrderEntrustType = DoRZRJQueryService.TypesRZRJOrderEntrustType.DIRECTSECURITYPAIDOFF;
                string errMsg = "";

                RZRQComputerResultEntity res = wcfService.getTradeMaxAmount(out errMsg, result);
                if (res == null)
                {
                    rtn.IsSuccess = false;
                    rtn.ErrorMsg = "根据输入信息无查询结果";
                    return rtn;
                }

                rtn.IsSuccess = true;
                rtn.AvailableMoney = res.CanUsePrice;
                rtn.DebitMoney = res.MaxCount;
                rtn.StockNumber = res.MaxCount;

                if (result.OrderEntrustType == DoRZRJQueryService.TypesRZRJOrderEntrustType.SELLSECURITYFORMONEYDEBT)
                {
                    result.OrderEntrustType = DoRZRJQueryService.TypesRZRJOrderEntrustType.DIRECTMONEYPAIDOFF;
                    RZRQComputerResultEntity tmp = wcfService.getTradeMaxAmount(out errMsg, result);
                    if (tmp != null)
                    {
                        rtn.DebitMoney = tmp.MaxCount;
                    }
                }

                return rtn;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询可操作最大股数失败" + ex.Message, null, null);
                throw new Exception("融资融券查询可操作最大股数失败", ex);
            }
        }

        [Remote("rzrjGetRjDebitQuty")]
        public RjDebitResult getRjDebitQuty(string userID, string pwd, string stockCode)
        {
            RZRJLiabilitiesFindEntity cond = new RZRJLiabilitiesFindEntity();
            cond.Code = stockCode;
            int total = 0;
            string errorMsg = "";
            DoRZRJQueryService.PagingInfo pagingInfo = new DoRZRJQueryService.PagingInfo();
            pagingInfo.CurrentPage = 1;
            pagingInfo.PageLength = 100;

            try
            {
                DoRZRJQueryService.RZRJ_RJLiabilities[] res = wcfService.getUnclosedRjLiabilities(out total, out errorMsg, userID, pwd, cond, pagingInfo);

                RjDebitResult rtn = new RjDebitResult();
                int quty = 0;
                if (res != null || res.Length > 0)
                {
                    foreach (DoRZRJQueryService.RZRJ_RJLiabilities r in res)
                    {
                        quty += Decimal.ToInt32(r.RJBuyAmount - r.PayBackSum);
                    }
                }
                rtn.IsSuccess = true;
                rtn.Message = "";
                rtn.RjDebitQuty = quty;
                return rtn;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询融券负债失败" + ex.Message, null, null);
                throw new Exception("融资融券查询融券负债失败", ex);
            }
        }

        [Remote("rzrjGetTodayOrder")]
        public RzrjTodayEntrustResult getRzrjTodayOrder(string userID, string pwd, int pageSize, int pageNo)
        {
            int total = 0;
            string errorMsg = ""; 
            RZRJEntrustConditionFindEntity cond = new RZRJEntrustConditionFindEntity(); 
            DoRZRJQueryService.PagingInfo pageInfo = new DoRZRJQueryService.PagingInfo();
            pageInfo.IsCount = true;
            pageInfo.CurrentPage = pageNo;
            pageInfo.PageLength = pageSize;

            try
            {
                RzrjTodayEntrustResult pagingRes = new RzrjTodayEntrustResult(); 
                RZRJ_TodayEntrust[] res = wcfService.getRzrjTodayOrder(out total, out errorMsg, userID, pwd, cond, pageInfo);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    return pagingRes;
                }
                pagingRes.Total = total;
                RZRJTodayEntrust[] tmp = new RZRJTodayEntrust[res.Length];
                int i = 0;
                foreach (RZRJ_TodayEntrust e in res)
                {
                    RZRJTodayEntrust m = new RZRJTodayEntrust();
                    m.CancelAmount = e.CancelAmount;
                    m.EntrustAmount = e.EntrustAmount;
                    m.EntrustNumber = e.EntrustNumber;
                    m.EntrustPrice = e.EntrustPrice;
                    m.EntrustTime = e.EntrustTime.ToString();
                    m.IsMarketValue = e.IsMarketValue;
                    m.OrderMessage = e.OrderMessage;
                    m.OrderStatusID = e.OrderStatusID;
                    m.OrderType = e.OrderType;
                    m.SpotCode = e.SpotCode;
                    m.TradeAmount = e.TradeAmount; 
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询当日委托失败" + ex.Message, null, null);
                throw new Exception("融资融券查询当日委托失败", ex);
            }
        }

        [Remote("rzrjGetHistoryOrder")]
        public RzrjTodayEntrustResult getRzrjHistoryOrder(string userID, string pwd, int pageSize, int pageNo)
        {
            int total = 0;
            string errorMsg = "";
            RZRJEntrustConditionFindEntity cond = new RZRJEntrustConditionFindEntity();
            DoRZRJQueryService.PagingInfo pageInfo = new DoRZRJQueryService.PagingInfo();
            pageInfo.IsCount = true;
            pageInfo.CurrentPage = pageNo;
            pageInfo.PageLength = pageSize;

            try
            {
                RzrjTodayEntrustResult pagingRes = new RzrjTodayEntrustResult();
                RZRJ_HistoryEntrust[] res = wcfService.getRzrjHistoryOrder(out total, out errorMsg, userID, pwd, cond, pageInfo);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    return pagingRes;
                }
                pagingRes.Total = total;
                RZRJTodayEntrust[] tmp = new RZRJTodayEntrust[res.Length];
                int i = 0;
                foreach (RZRJ_HistoryEntrust e in res)
                {
                    RZRJTodayEntrust m = new RZRJTodayEntrust();
                    m.CancelAmount = e.CancelAmount;
                    m.EntrustAmount = e.EntrustAmount;
                    m.EntrustNumber = e.EntrustNumber;
                    m.EntrustPrice = e.EntrustPrice;
                    m.EntrustTime = e.EntrustTime.ToString();
                    m.IsMarketValue = e.IsMarketValue;
                    m.OrderMessage = e.OrderMessage;
                    m.OrderStatusID = e.OrderStatusID;
                    m.OrderType = e.OrderType;
                    m.SpotCode = e.SpotCode;
                    m.TradeAmount = e.TradeAmount;
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询历史委托失败" + ex.Message, null, null);
                throw new Exception("融资融券查询历史委托失败", ex);
            }
        }

        [Remote("rzrjGetTodayTrade")]
        public TodayTradeResult getRzrjTodayTrade(string userID, string pwd, int pageSize, int pageNo)
        {
            int total = 0;
            string errorMsg = "";
            RZRJTradeConditionFindEntity cond = new RZRJTradeConditionFindEntity(); 
            DoRZRJQueryService.PagingInfo pageInfo = new DoRZRJQueryService.PagingInfo();
            pageInfo.IsCount = true;
            pageInfo.CurrentPage = pageNo;
            pageInfo.PageLength = pageSize;
            try
            {
                TodayTradeResult pagingRes = new TodayTradeResult();
                RZRJ_TodayTrade[] res = wcfService.getRzrjTodayTrade(out total, out errorMsg, userID, pwd, cond, pageInfo);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    return pagingRes;
                }
                pagingRes.Total = total;
                TodayTrade[] tmp = new TodayTrade[res.Length];
                int i = 0;
                foreach (RZRJ_TodayTrade e in res)
                {
                    TodayTrade m = new TodayTrade();
                    m.SpotCode = e.SpotCode;
                    m.TradeTime = e.TradeTime.ToString();
                    m.TradePrice = e.TradePrice;
                    m.TradeAmount = e.TradeAmount;
                    m.TradeCapitalAmount = e.TradeCapitalAmount;
                    m.Commission = e.Commission;
                    m.StampTax = e.StampTax;
                    m.ClearingFee = e.ClearingFee;
                    m.MonitoringFee = e.MoitoringFee;
                    m.TradeProceduresFee = e.TradeProceduresFee;    //过户费，融资融券中为TradeProceduresFee字段
                    m.TransferAccountFee = 0;                       //过户费，现货中为TransferAccountFee字段
                    m.TradingSystemUseFee = e.TradingSystemUseFee;
                    m.TradeTypeId = e.TradeTypeID;
                    m.BuySellTypeId = e.BuySellTypeID;
                    m.OrderType = e.OrderType;
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询当日成交失败" + ex.Message, null, null);
                throw new Exception("融资融券查询当日成交失败", ex);
            }
        }

        [Remote("rzrjGetHistoryTrade")]
        public TodayTradeResult getRzrjHistoryTrade(string userID, string pwd, int pageSize, int pageNo)
        {
            int total = 0;
            string errorMsg = "";
            RZRJTradeConditionFindEntity cond = new RZRJTradeConditionFindEntity();
            DoRZRJQueryService.PagingInfo pageInfo = new DoRZRJQueryService.PagingInfo();
            pageInfo.IsCount = true;
            pageInfo.CurrentPage = pageNo;
            pageInfo.PageLength = pageSize;
            try
            {
                TodayTradeResult pagingRes = new TodayTradeResult();
                RZRJ_HistoryTrade[] res = wcfService.getRzrjHistoryTrade(out total, out errorMsg, userID, pwd, cond, pageInfo);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    return pagingRes;
                }
                pagingRes.Total = total;
                TodayTrade[] tmp = new TodayTrade[res.Length];
                int i = 0;
                foreach (RZRJ_HistoryTrade e in res)
                {
                    TodayTrade m = new TodayTrade();
                    m.SpotCode = e.SpotCode;
                    m.TradeTime = e.TradeTime.ToString();
                    m.TradePrice = e.TradePrice;
                    m.TradeAmount = e.TradeAmount;
                    m.TradeCapitalAmount = e.TradeCapitalAmount;
                    m.Commission = e.Commission;
                    m.StampTax = e.StampTax;
                    m.ClearingFee = e.ClearingFee;
                    m.MonitoringFee = e.MoitoringFee;
                    m.TradeProceduresFee = e.TradeProceduresFee;
                    m.TransferAccountFee = 0;
                    m.TradingSystemUseFee = e.TradingSystemUseFee;
                    m.TradeTypeId = e.TradeTypeID;
                    m.BuySellTypeId = e.BuySellTypeID;
                    m.OrderType = e.OrderType;
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询历史成交失败" + ex.Message, null, null);
                throw new Exception("融资融券查询历史成交失败", ex);
            }
        }

        [Remote("rzrjGetAccountHoldDetail")]
        public RzrjAccountHoldResult getRzrjAccountHoldDetail(string userId, string strPassword, int pageSize, int pageNo)
        {
            RZRJHoldConditionFindEntity cond = new RZRJHoldConditionFindEntity();
            int count = 0;
            int start = pageNo;
            int pageLength = pageSize;
            string strErrorMessage = "";

            try
            {
                RZRJHoldFindResultEntity[] res = wcfService.getRzrjAccountHoldDetail(out count, userId, strPassword, cond, start, pageLength, ref strErrorMessage);
                if (res == null || res.Length <= 0)
                {
                    return null;
                }
                RzrjAccountHoldResult pagingRes = new RzrjAccountHoldResult();
                pagingRes.Total = count;
                pagingRes.ResultList = res;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询持仓详细信息失败" + ex.Message, null, null);
                throw new Exception("融资融券查询持仓详细信息失败", ex);
            }
        }

        [Remote("rzrjGetAccountHoldSimple")]
        public RZRJ_HoldAccount[] getRzrjAccountHoldSimple(string userId)
        {
            try
            {
                string errorMsg = "";
                RZRJ_HoldAccount[] res = wcfService.getRzrjAccountHoldSimple(out errorMsg, userId, QueryTypeQueryCurrencyType.RMB);
                return res;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询持仓简单信息失败" + ex.Message, null, null);
                throw new Exception("融资融券查询持仓简单信息失败", ex);
            }
        }

        [Remote("rzrjGetCapital")]
        public RZRJCapitalEntity getRzrjCapital(string strFundAccountId, string userPassword)
        {
            try
            {
                string strErrorMessage = "";
                RZRJCapitalEntity res = wcfService.getRzrjCapital(strFundAccountId, 1, userPassword, ref strErrorMessage);
                return res;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询资产信息失败" + ex.Message, null, null);
                throw new Exception("融资融券查询资产信息失败", ex);
            }
        }

        [Remote("rzrjGetRzrjCreditAsset")]
        public RzrjCreditInfoResult getRzrjCreditAsset(string userID, string pwd)
        {
            string errorMsg = "";
            int currencyType = 1;

            try
            {
                RZRQCreditAssetsEntity res = wcfService.getRzrjCreditAsset(out errorMsg, userID, pwd, currencyType);
                RzrjCreditInfoResult msg = new RzrjCreditInfoResult();
                if (res != null)
                {
                    msg.AllLiabilitiesSum = res.AllLiabilitiesSum;
                    msg.AllMarketValueOfSecurities = res.AllMarketValueOfSecurities;
                    msg.AvailableMargin = res.AvailableMargin;
                    msg.CashAssets = res.CashAssets;
                    msg.DirectMoneyPaidOffSum = res.DirectMoneyPaidOffSum;
                    msg.ExtractableAmount = res.ExtractableAmount;
                    msg.LiabilitiesSum = res.LiabilitiesSum;
                    msg.NotDoneProfitLossTotal = res.NotDoneProfitLossTotal;
                    msg.RQLiabilitiesSum = res.RQLiabilitiesSum;
                    msg.RQLimitCredit = res.RQLimitCredit;
                    msg.RQOccupyMargin = res.RQOccupyMargin;
                    msg.RQProfit = res.RQProfit;
                    msg.RZLimitCredit = res.RZLimitCredit;
                    msg.RZmarketValueRateSum = res.RZmarketValueRateSum;
                    msg.RZOccupyMargin = res.RZOccupyMargin;
                    msg.RZProfit = res.RZProfit;

                    //保证金比例
                    decimal maintainGuarantyRatio = 0.0M;
                    bool isGuaranty = wcfService.getMaintainGuarantyRatio(out maintainGuarantyRatio, out errorMsg, userID, pwd, currencyType);
                    msg.IsGuaranty = isGuaranty;
                    msg.MaintainGuarantyRatio = maintainGuarantyRatio;

                    //利息
                    RZRJ_CapitalExtendTable[] exts = wcfService.getRzrjCapitalExtendTable(out errorMsg, userID, pwd, 1);
                    if (exts != null && exts.Length > 0)
                    {
                        RZRJ_CapitalExtendTable ext = exts[0];
                        msg.RJInterest = ext.RQInterest;
                        msg.RZInterest = ext.RZInterest;
                        msg.FinedInterest = ext.Charge;
                        msg.OverDueFee = ext.LateCharge;
                    } 
                }
                return msg;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询客户信用资产失败" + ex.Message, null, null);
                throw new Exception("融资融券查询客户信用资产失败", ex);
            }
        }


        [Remote("rzrjGetMaintainGuarantyRatio")]
        public RzrjCreditInfoResult getMaintainGuarantyRatio(string userID, string pwd)
        {
            string errorMsg = "";
            int currencyType = 1;
            decimal maintainGuarantyRatio = 0.0M;
            try
            {
                bool isGuaranty = wcfService.getMaintainGuarantyRatio(out maintainGuarantyRatio, out errorMsg, userID, pwd, currencyType);
                RzrjCreditInfoResult msg = new RzrjCreditInfoResult();
                msg.IsGuaranty = isGuaranty;
                msg.MaintainGuarantyRatio = maintainGuarantyRatio;
                return msg;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询客户担保比例失败" + ex.Message, null, null);
                throw new Exception("融资融券查询客户担保比例失败", ex);
            }
        }

        [Remote("rzrjGetUnclosedRzLiabilities")]
        public RzrjLiabilitiesResult[] getUnclosedRzLiabilities(string userID, string pwd, int pageSize, int pageNo, int isProcessing)
        {
            //查询未了结融资合约 
            RZRJLiabilitiesFindEntity cond = new RZRJLiabilitiesFindEntity(); 
            cond.IsProcessing = isProcessing == 1? true:false;  
            DoRZRJQueryService.PagingInfo pagingInfo = new DoRZRJQueryService.PagingInfo();
            pagingInfo.IsCount = true;
            pagingInfo.CurrentPage = pageNo;
            pagingInfo.PageLength = pageSize;
            int total = 0;
            string errorMsg = "";

            try
            {
                DoRZRJQueryService.RZRJ_Liabilities[] res = wcfService.getUnclosedRzLiabilities(out total, out errorMsg, userID, pwd, cond, pagingInfo);

                if (res == null || res.Length <= 0)
                {
                    return null;
                }

                RzrjLiabilitiesResult[] rMsg = new RzrjLiabilitiesResult[res.Length];
                int i = 0;
                foreach (DoRZRJQueryService.RZRJ_Liabilities r in res)
                {
                    RzrjLiabilitiesResult m = new RzrjLiabilitiesResult();
                    m.Total = total;
                    m.Code = r.Code;
                    m.BusinessFlag = 1;
                    m.CostAmount = r.RZBuyLiabilitiesSum - r.RZBuyAmount * r.TradePrice;
                    m.RZBuyLiabilitiesSum = r.RZBuyLiabilitiesSum;
                    m.BuyAmount = r.RZBuyAmount;
                    m.PayBackSum = r.PayBackSum;
                    m.TradePrice = r.TradePrice;
                    m.InterestSum = r.RZInterestSum;
                    m.PayBackInterestSum = r.PayBackRZInterestSum;
                    m.LiabilitiesStartDate = r.LiabilitiesStartDate.ToString();
                    m.LiabilitiesEndDate = r.LiabilitiesEndDate.ToString();
                    m.IsProcessing = r.IsProcessing;
                    rMsg[i++] = m;
                }
                return rMsg;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询未关闭融资合约失败" + ex.Message, null, null);
                throw new Exception("融资融券查询未关闭融资合约失败", ex);
            }
        }

        [Remote("rzrjGetClosedRzLiabilities")]
        public RzrjLiabilitiesResult[] getClosedRzLiabilities(string userID, string pwd, int pageSize, int pageNo, int isProcessing)
        {
            //查询已了结融资合约 
            RZRJLiabilitiesFindEntity cond = new RZRJLiabilitiesFindEntity();
            int total = 0;
            string errorMsg = ""; 
            DoRZRJQueryService.PagingInfo pagingInfo = new DoRZRJQueryService.PagingInfo();
            pagingInfo.IsCount = true;
            pagingInfo.CurrentPage = pageNo;
            pagingInfo.PageLength = pageSize;

            try
            {
                DoRZRJQueryService.RZRQ_LiabilitiesHistory[] res = wcfService.getClosedRzLiabilities(out total, out errorMsg, userID, pwd, cond, pagingInfo);
                if (res == null || res.Length <= 0)
                {
                    return null;
                }

                RzrjLiabilitiesResult[] rMsg = new RzrjLiabilitiesResult[res.Length];
                int i = 0;
                foreach (RZRQ_LiabilitiesHistory r in res)
                {
                    RzrjLiabilitiesResult m = new RzrjLiabilitiesResult();
                    m.Total = total;
                    m.Code = r.Code;
                    m.CostAmount = r.RZBuyLiabilitiesSum - r.RZBuyAmount * r.TradePrice;
                    m.RZBuyLiabilitiesSum = r.RZBuyLiabilitiesSum;
                    m.BuyAmount = r.RZBuyAmount;
                    m.PayBackSum = r.PayBackSum;
                    m.TradePrice = r.TradePrice;
                    m.InterestSum = r.RZInterestSum;
                    m.PayBackInterestSum = r.PayBackRZInterestSum;
                    m.FinishedDate = r.FinishedDate.ToString();
                    m.LiabilitiesStartDate = r.LiabilitiesStartDate.ToString();
                    m.LiabilitiesEndDate = r.LiabilitiesEndDate.ToString();
                    m.IsProcessing = r.IsProcessing;
                    rMsg[i++] = m;
                }
                return rMsg;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询已关闭融资合约失败" + ex.Message, null, null);
                throw new Exception("融资融券查询已关闭融资合约失败", ex);
            }
        }

        [Remote("rzrjGetUnclosedRjLiabilities")]
        public RzrjLiabilitiesResult[] getUnclosedRjLiabilities(string userID, string pwd, int pageSize, int pageNo, int isProcessing)
        { 
            RZRJLiabilitiesFindEntity cond = new RZRJLiabilitiesFindEntity();
            int total = 0;
            string errorMsg = ""; 
            DoRZRJQueryService.PagingInfo pagingInfo = new DoRZRJQueryService.PagingInfo();
            pagingInfo.IsCount = true;
            pagingInfo.CurrentPage = pageNo;
            pagingInfo.PageLength = pageSize;

            try
            {
                DoRZRJQueryService.RZRJ_RJLiabilities[] res = wcfService.getUnclosedRjLiabilities(out total, out errorMsg, userID, pwd, cond, pagingInfo);

                if (res == null || res.Length <= 0)
                {
                    return null;
                }

                RzrjLiabilitiesResult[] rMsg = new RzrjLiabilitiesResult[res.Length];
                int i = 0;
                foreach (DoRZRJQueryService.RZRJ_RJLiabilities r in res)
                {
                    RzrjLiabilitiesResult m = new RzrjLiabilitiesResult();
                    m.Total = total;
                    m.Code = r.Code;
                    m.BusinessFlag = 2;
                    m.CostAmount = r.CostAmount;
                    m.BuyAmount = r.RJBuyAmount;
                    m.PayBackSum = r.PayBackSum;
                    m.TradePrice = r.TradePrice;
                    m.InterestSum = r.RQInterestSum;
                    m.PayBackInterestSum = r.PayBackRQInterestSum;
                    m.LiabilitiesStartDate = r.LiabilitiesStartDate.ToString();
                    m.LiabilitiesEndDate = r.LiabilitiesEndDate.ToString();
                    m.IsProcessing = r.IsProcessing;
                    rMsg[i++] = m;

                }
                return rMsg;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询未关闭融券合约失败" + ex.Message, null, null);
                throw new Exception("融资融券查询未关闭融券合约失败", ex);
            }
        }

        [Remote("rzrjGetClosedRjLiabilities")]
        public RzrjLiabilitiesResult[] getClosedRjLiabilities(string userID, string pwd, int pageSize, int pageNo, int isProcessing)
        {
            //查询已了结融券合约 
            RZRJLiabilitiesFindEntity cond = new RZRJLiabilitiesFindEntity();
            if (isProcessing != -1)
            {
                cond.IsProcessing = isProcessing == 1 ? true : false;
            } 
            int total = 0;
            string errorMsg = ""; 
            DoRZRJQueryService.PagingInfo pagingInfo = new DoRZRJQueryService.PagingInfo();
            pagingInfo.IsCount = true;
            pagingInfo.CurrentPage = pageNo;
            pagingInfo.PageLength = pageSize;

            try
            {
                RZRQ_RQLiabilitiesHistory[] res = wcfService.getClosedRjLiabilities(out total, out errorMsg, userID, pwd, cond, pagingInfo);

                if (res == null || res.Length <= 0)
                {
                    return null;
                }

                RzrjLiabilitiesResult[] rMsg = new RzrjLiabilitiesResult[res.Length];
                int i = 0;
                foreach (RZRQ_RQLiabilitiesHistory r in res)
                {
                    RzrjLiabilitiesResult m = new RzrjLiabilitiesResult();
                    m.Total = total;
                    m.Code = r.Code;
                    m.CostAmount = r.CostAmount;
                    m.BuyAmount = r.RJBuyAmount;
                    m.PayBackSum = r.PayBackSum;
                    m.TradePrice = r.TradePrice;
                    m.InterestSum = r.RQInterestSum;
                    m.PayBackInterestSum = r.PayBackRQInterestSum;
                    m.FinishedDate = r.FinishedDate.ToString();
                    m.LiabilitiesStartDate = r.LiabilitiesStartDate.ToString();
                    m.LiabilitiesEndDate = r.LiabilitiesEndDate.ToString();
                    m.IsProcessing = r.IsProcessing;
                    rMsg[i++] = m;
                }
                return rMsg;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询已关闭融券合约失败" + ex.Message, null, null);
                throw new Exception("融资融券查询已关闭融券合约失败", ex);
            }
        } 


        /*****标的物*****/
        [Remote("rzrjGetUnderLyingList")]
        public RzrjUnderLyingResult getRzrjUnderLyingList(int securityCompanyID, string code, int pageSize, int pageNo)
        {
            string message = ""; 
            int total = 0;
            MPagingInfo pagingInfo = new MPagingInfo();
            pagingInfo.IsCount = true;
            pagingInfo.CurrentPage = pageNo;
            pagingInfo.PageLength = pageSize;

            try
            {
                RZRJ_BourseUnderlyingCode[] res = wcfService.getRzrjUnderLyingList(out total, out message, code, pagingInfo);
                if (res == null || res.Length <= 0)
                {
                    return null;
                }

                string tmpCode = "";
                foreach (RZRJ_BourseUnderlyingCode d in res)
                {
                    tmpCode = d.Code;
                    RZRJ_SecurityUnderlyingCode[] s = wcfService.getRzrjCompanyUnderLyingCode(securityCompanyID, tmpCode);
                    if (s != null && s.Length > 0 && s[0] != null)
                    {
                        d.IsAllowRJ = s[0].IsSecurities;
                        d.IsAllowRZ = s[0].ISFinancing; 
                    }
                }

                RzrjUnderLyingResult pagingRes = new RzrjUnderLyingResult();
                pagingRes.Total = total;
                pagingRes.ResultList = res;
                return pagingRes; 
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询标的物失败" + ex.Message, null, null);
                throw new Exception("融资融券查询标的物失败", ex); 
            }
        }

        [Remote("rzrjIsUnderLyingStock")]
        public bool isUnderLyingStock(string companyId, string code)
        {
            string message = ""; 
            try
            {
                return wcfService.isUnderLyingStock(out message, code);
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券判断是否标的物失败" + ex.Message, null, null);
                throw new Exception("融资融券判断是否标的物失败", ex);
            }
        }

        /*
        [Remote("rzrjGetCompanyUnderLyingList")]
        public RzrjUnderLyingResult getRzrjCompanyUnderLyingList(int securityCompanyID, string code, int pageSize, int pageNo)
        {
            string msg = "";
            int total = 0;
            MPagingInfo pagingInfo = new MPagingInfo();
            pagingInfo.IsCount = true;
            pagingInfo.CurrentPage = pageNo;
            pagingInfo.PageLength = pageSize; 
            RZRJ_SecurityUnderlyingCode[] res = wcfService.getRzrjCompanyUnderLyingList(out total, out msg, securityCompanyID, code, pagingInfo);

            if (res == null || res.Length <= 0)
            {
                return null;
            }

            RzrjUnderLyingResult pagingRes = new RzrjUnderLyingResult();
            pagingRes.Total = total;
            pagingRes.ResultList = res;
            return pagingRes;
        }*/

        /*****担保品******/
        [Remote("rzrjGetMortagageList")]
        public RzrjMortagageResult getRzrjMortagageList(string code, int codeBelongBourse, int priorLevel, int pageSize, int pageNo)
        {
            string message = "";  
            int total = 0; 
            MPagingInfo pagingInfo = new MPagingInfo();
            pagingInfo.IsCount = true;
            pagingInfo.CurrentPage = pageNo;
            pagingInfo.PageLength = pageSize;

            try
            {
                RZRJ_BourseMortagagedCode[] res = wcfService.getRzrjMortagageList(out total, out message, code, codeBelongBourse, priorLevel, pagingInfo);

                if (res == null || res.Length <= 0)
                {
                    return null;
                }

                RzrjMortagageResult pagingRes = new RzrjMortagageResult();
                pagingRes.Total = total;
                pagingRes.ResultList = res;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券查询担保品失败" + ex.Message, null, null);
                throw new Exception("融资融券查询担保品失败", ex);
            }
        }

        [Remote("rzrjIsMortagageStock")]
        public bool isMortagageStock(string companyId, string code)
        {
            string message = "";

            try
            {
                return wcfService.isMortagageStock(out message, code);
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("融资融券判断是否担保品失败" + ex.Message, null, null);
                throw new Exception("融资融券判断是否担保品失败", ex);
            }
        } 

        /*
        [Remote("rzrjGetCompanyMortagageList")]
        public RZRJ_SecurityMortagagedCode[] getRzrjCompanyMortagageList(string code, int securityCompanyID, int pageSize, int pageNo)
        {
            string msg = "";
            int total = 0;
            MPagingInfo pagingInfo = new MPagingInfo();
            pagingInfo.IsCount = true;
            pagingInfo.CurrentPage = pageNo;
            pagingInfo.PageLength = pageSize;
            
            RZRJ_SecurityMortagagedCode[] res = wcfService.getRzrjCompanyMortagageList(out total, out msg, code, securityCompanyID, pagingInfo);
            return res;
        }
        */ 
        
    }

    class RzrjLiabilitiesResult
    {  
        public int Total { get; set; }  

        public string Code { get; set; }

        public int BusinessFlag { get; set; }

        public decimal CostAmount { get; set; }

        public decimal BuyAmount { get; set; }

        public decimal RZBuyLiabilitiesSum { get; set; } 

        public decimal PayBackSum { get; set; }

        public decimal TradePrice { get; set; }

        public decimal InterestSum { get; set; }

        public decimal PayBackInterestSum { get; set; }

        public string FinishedDate { get; set; }

        public string LiabilitiesStartDate { get; set; }

        public string LiabilitiesEndDate { get; set; }

        public bool IsProcessing { get; set; } 
    }

    class RzrjUnderLyingResult
    {
        public int Total { get; set; }

        public RZRJ_BourseUnderlyingCode[] ResultList { get; set; }
    }

    class RzrjMortagageResult
    {
        public int Total { get; set; }

        public RZRJ_BourseMortagagedCode[] ResultList { get; set; }
    } 

    class RzrjCancelOrderResult
    {
        public bool IsSuccess { get; set; }

        public string Message { get; set; }
    }

    class RjDebitResult
    {
        public bool IsSuccess { get; set; }

        public string Message { get; set; }

        public int RjDebitQuty { get; set; }
    }

    class RzrjTodayEntrustResult
    {
        public int Total { get; set; }

        public RZRJTodayEntrust[] ResultList { get; set; } 
    }

    class RZRJTodayEntrust
    {
        public string SpotCode{ get; set; } 
        public int OrderType{ get; set; } 
        public decimal EntrustPrice{ get; set; }
        public decimal EntrustAmount { get; set; } 
        public bool IsMarketValue{ get; set; } 
        public int OrderStatusID{ get; set; } 
        public string EntrustTime{ get; set; } 
        public string OrderMessage{ get; set; } 
        public string EntrustNumber{ get; set; }
        public decimal TradeAmount { get; set; }
        public decimal CancelAmount { get; set; } 
    }

    class RzrjAccountHoldResult
    {
        public int Total { get; set; }

        public RZRJHoldFindResultEntity[] ResultList { get; set; }
    }

    class RzrjCreditInfoResult
    {
        public decimal AllLiabilitiesSum { get; set; }

        public decimal AllMarketValueOfSecurities { get; set; }

        public decimal AvailableMargin { get; set; }

        public decimal CashAssets { get; set; }

        public decimal DirectMoneyPaidOffSum { get; set; }

        public decimal ExtractableAmount { get; set; }

        public decimal LiabilitiesSum { get; set; }

        public decimal NotDoneProfitLossTotal { get; set; }
        
        public decimal RQLiabilitiesSum { get; set; }
        
        public decimal RQLimitCredit { get; set; }
        
        public decimal RQOccupyMargin { get; set; }
        
        public decimal RQProfit { get; set; }
        
        public decimal RZLimitCredit { get; set; }
        
        public decimal RZmarketValueRateSum { get; set; }
        
        public decimal RZOccupyMargin { get; set; }
        
        public decimal RZProfit { get; set; }
        
        public bool IsGuaranty { get; set; }
        
        public decimal MaintainGuarantyRatio { get; set; } 

        public decimal RZInterest { get; set; }

        public decimal RJInterest { get; set; }

        public decimal FinedInterest { get; set; }

        public decimal OverDueFee { get; set; }

    }

    class TradeMaxAmountResult
    {
        public bool IsSuccess { get; set; }

        public string ErrorMsg { get; set; }

        public decimal AvailableMoney { get; set; }

        public decimal DebitMoney { get; set; }

        public decimal StockNumber { get; set; }
    }


}
